package com.hth.main;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.Socket;

public class ClientTCPTest {
	
	public ClientTCPTest(String ipServer, int port, String message) {
		try {
			System.out.println("Connect server: " + ipServer + " : " + port);
			Socket client = new Socket(ipServer, port);
			System.out.println("Just connected to " + client.getRemoteSocketAddress());
			
			// gửi dữ liệu lên server:
			OutputStream outToServer = client.getOutputStream();
			PrintWriter printWriter = new PrintWriter(outToServer, true);
			printWriter.println(message);
			
			// nhận dữ liệu từ server:
			InputStream inFromServer = client.getInputStream();
			BufferedReader bufferedReader = 
					new BufferedReader(new InputStreamReader(inFromServer));
			String dataFromServer = null;
			System.out.println("Server nói: ");
			while ((dataFromServer = bufferedReader.readLine()) != null) {
			      System.out.println(dataFromServer);
			}
			
			outToServer.close();
			inFromServer.close();
			bufferedReader.close();
			printWriter.close();
			client.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
